package com.maserb.monitor.database;

import com.maserb.monitor.entity.TreeNodeEntity;
import com.maserb.monitor.repository.TreeNodeRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

@Component
public class JdbcTemplateFactory {
    private ConcurrentMap<String, JdbcTemplate> jdbcTemplatePool = new ConcurrentHashMap<>();

    @Value("${monitor.datasource.driverClassName}")
    private String jdbcDriver;

    @Value("${monitor.datasource.username}")
    private String username;

    @Value("${monitor.datasource.password}")
    private String password;

    @Value("${monitor.datasource.url}")
    private String url;

    @Autowired
    TreeNodeRepository treeNodeRepository;

    public void init() {
        Iterable<TreeNodeEntity> list = treeNodeRepository.findAll();
        if (list != null) {
            for (TreeNodeEntity node : list) {
                if (node.getCode() != null) {
                    JdbcTemplate jdbcTemplate = getTemplate(node.getCode());
                    jdbcTemplatePool.put(node.getCode(), jdbcTemplate);
                }
            }
        }
    }

    public JdbcTemplate getTemplate(String code) {
        JdbcTemplate jdbcTemplate = null;

        try {
            if (!jdbcTemplatePool.containsKey(code)) {
                createMyDatabase(code);
                jdbcTemplate = createJdbcTemplate(code);
                jdbcTemplatePool.put(code, jdbcTemplate);
            } else {
                jdbcTemplate = jdbcTemplatePool.get(code);
            }
        } catch (Exception e) {

        }

        return jdbcTemplate;
    }

    private JdbcTemplate createJdbcTemplate(String code) {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName(jdbcDriver);
        dataSource.setUrl(url + code);
        dataSource.setUsername(username);
        dataSource.setPassword(password);

        return new JdbcTemplate(dataSource);
    }

    /**
     * 创建数据库
     */
    public void createMyDatabase(String dbname) {
        DeviceDatabaseCreator creator = new DeviceDatabaseCreator();
        creator.create(jdbcDriver, url, username, password, dbname);
        createMyTables(dbname);
    }

    /**
     * 创建相关表
     */
    public void createMyTables(String dbname) {
        DeviceTablesCreator creator = new DeviceTablesCreator();
        creator.create(jdbcDriver, url, username, password, dbname);
    }
}
